<template>
  <nav class="navbar" :key="forceUpdateKey">
    <div class="navbar-content">
      <router-link to="/" class="logo">RedBook</router-link>
      <div class="search-box">
        <input type="text" placeholder="搜索" class="search-input">
        <i class="search-icon">🔍</i>
      </div>
      <div class="nav-items">
        <router-link to="/" class="nav-item">首页</router-link>
        <router-link to="/create" class="nav-item" v-if="isLoggedIn">发布</router-link>
        <router-link to="/login" class="nav-item" v-if="!isLoggedIn">登录</router-link>
        <router-link to="/register" class="nav-item" v-if="!isLoggedIn">注册</router-link>
        <div class="user-menu" v-if="isLoggedIn">
          <div class="user-avatar" @click="$router.push('/profile')">
            <img v-if="avatar && avatar !== 'null' && avatar !== 'undefined'" :src="($http.defaults.baseURL.replace(/\/$/, '') + avatar)" alt="用户头像" class="avatar-image" @error="handleAvatarError">
            <span v-else>{{ username.charAt(0) }}</span>
          </div>
          <div class="menu-dropdown">
            <router-link to="/profile" class="menu-item">我的主页</router-link>
            <button @click="logout" class="menu-item">退出登录</button>
          </div>
        </div>
      </div>
    </div>
  </nav>
</template>

<script>
export default {
  data() {
    return {
      // 用于强制刷新计算属性
      refreshKey: 0,
      // 用于强制组件重新渲染
      forceUpdateKey: 0
    }
  },
  computed: {
    isLoggedIn() {
      // 依赖 refreshKey 强制刷新
      this.refreshKey;
      return !!localStorage.getItem('token');
    },
    username() {
      // 依赖 refreshKey 强制刷新
      this.refreshKey;
      return localStorage.getItem('username') || '';
    },
    avatar() {
      // 依赖 refreshKey 强制刷新
      this.refreshKey;
      const avatar = localStorage.getItem('avatar') || '';
      console.log('Avatar from localStorage:', avatar);
      return avatar;
    }
  },
  methods: {
    logout() {
      localStorage.removeItem('token');
      localStorage.removeItem('userId');
      localStorage.removeItem('username');
      localStorage.removeItem('avatar');
      
      // 触发storage事件通知其他组件
      window.dispatchEvent(new Event('storage'));
      
      // 强制刷新页面以确保所有组件重新加载
      setTimeout(() => {
        window.location.href = '/login';
      }, 100);
    },
    handleStorageChange(e) {
      // 当 token、username 或 avatar 发生变化时刷新
      if (e.key === 'token' || e.key === 'username' || e.key === 'avatar') {
        this.refreshKey += 1;
        this.forceUpdateKey += 1; // 强制组件重新渲染
      }
    },
    handleAvatarError() {
      console.log('Avatar image failed to load, clearing avatar');
      console.log('Failed avatar URL:', this.$http.defaults.baseURL + this.avatar);
      localStorage.removeItem('avatar');
      this.refreshKey += 1;
      this.forceUpdateKey += 1;
    }
  },
  mounted() {
    // 监听 storage 事件，跨标签页同步登录状态
    window.addEventListener('storage', this.handleStorageChange);
    
    // 添加调试信息
    console.log('NavBar mounted, avatar:', this.avatar);
    console.log('NavBar mounted, isLoggedIn:', this.isLoggedIn);
    
    // 强制刷新一次确保状态正确
    this.refreshKey += 1;
    this.forceUpdateKey += 1;
  },
  beforeDestroy() {
    window.removeEventListener('storage', this.handleStorageChange);
  }
}
</script>

<style scoped>
.navbar {
  background: white;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #ff2449;
  text-decoration: none;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-input {
  width: 100%;
  padding: 8px 15px 8px 35px;
  border: 1px solid #eee;
  border-radius: 20px;
  background: #f8f8f8;
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.nav-items {
  display: flex;
  align-items: center;
}

.nav-item {
  margin-left: 25px;
  color: #333;
  text-decoration: none;
  font-weight: 500;
}

.user-menu {
  position: relative;
  margin-left: 25px;
  cursor: pointer;
}

.user-avatar {
  width: 36px;
  height: 36px;
  background: #ff2449;
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  cursor: pointer;
  overflow: hidden;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.menu-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  background: white;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  padding: 10px 0;
  min-width: 120px;
  display: none;
}

.user-menu:hover .menu-dropdown {
  display: block;
}

.menu-item {
  display: block;
  width: 100%;
  padding: 8px 15px;
  text-align: left;
  background: none;
  border: none;
  cursor: pointer;
}

.menu-item:hover {
  background: #f8f8f8;
}

/* 为router-link添加样式 */
.menu-item {
  display: block;
  width: 100%;
  padding: 8px 15px;
  text-align: left;
  background: none;
  border: none;
  cursor: pointer;
  color: #333;
  text-decoration: none;
  font-size: 14px;
}
</style>